import { useAddCommodityType } from '@/services/pages/param-set/commodity-set'
import { useAddNetworkType } from '@/services/pages/param-set/network-set'
import { useAddOrderType } from '@/services/pages/param-set/order-set'
import { computed } from 'vue'
import { AddTypeForm } from './types'

const {
  addCommodityTypeForm,
  resetAddCommodityTypeForm,
  addCommodityType,
  addCommodityTypeLoading,
} = useAddCommodityType()

const { addNetworkTypeForm, addNetworkTypeLoading, addNetworkType, resetAddNetworkTypeForm } =
  useAddNetworkType()

const { addOrderTypeForm, addOrderTypeLoading, addOrderType, resetAddOrderTypeForm } =
  useAddOrderType()

export default (type: 'commodity' | 'order' | 'network') => {
  const formMap = {
    commodity: addCommodityTypeForm,
    network: addNetworkTypeForm,
    order: addOrderTypeForm,
  }

  const form: AddTypeForm = formMap[type]

  const submit = async (orderModuleId?: string) => {
    if (type === 'commodity') {
      return await addCommodityType()
    }

    if (type === 'network') {
      return await addNetworkType()
    }

    if (type === 'order' && orderModuleId) {
      return await addOrderType(orderModuleId)
    }
  }

  const resetForm = () => {
    switch (type) {
      case 'commodity':
        resetAddCommodityTypeForm()
        break
      case 'network':
        resetAddNetworkTypeForm()
        break
      case 'order':
        resetAddOrderTypeForm()
        break
    }
  }

  const loading = computed(() => {
    return addCommodityTypeLoading.value || addNetworkTypeLoading.value || addOrderTypeLoading.value
  })

  return {
    form,
    loading,
    submit,
    resetForm,
  }
}
